import wxsdk3 from "./wxsdk3.3.0.js"; // 3.0sdk
import config from "./utils/WebIMConfig.js"; // 3.0sdk
import $tool from '@/common/Tools/index.js'
import $pub from '@/common/public/index.js'

import {
	API$SelNickNameAvar
} from '@/common/API/HuanXinIM.js'
//实例化SDK对象
const WebIM = wx.WebIM = wxsdk3;

WebIM.configsss = config
WebIM.conn = new WebIM.connection({
	appKey: config.appKey, // AppKey
	isMultiLoginSessions: config.isMultiLoginSessions, //是否可以登录多个，并在所有端上接收消息
	https: false, //是否使用HTTPS 
	url: config.url, // socket server (3.0 SDK)
	apiUrl: config.apiUrl, // rest server
	isAutoLogin: config.isAutoLogin, // 是否自动登录
	heartBeatWait: config.heartBeatWait, //心跳间隔
	autoReconnectNumMax: config.autoReconnectNumMax, //自动重连次数
	useOwnUploadFun: config.useOwnUploadFun, // 是否使用自己的上传方式（如将图片文件等上传到自己的服务器，构建消息时只传url）
	autoReconnectInterval: config.autoReconnectInterval
});

WebIM.conn.listen({
	onOpened: function(message) {
		console.warn('连接成功', message)
	},
	onClosed: function(message) {
		console.warn('连接关闭', message)
	},
	onTextMessage: async function(message) {
		console.warn('收到文本消息', message)
		let chatHistroy = uni.getStorageSync(`chatHistroy_${uni.getStorageSync('UserInfo')._id}`) // 取当前账号下全部聊天缓存

		// 存在
		if (chatHistroy) {
			console.log('是用一个用户发送的')
			let indexs = chatHistroy.findIndex(i => i.to === message.from);
			if (indexs != -1) {
				let addJSON = {
					SendType: message.contentsType.toLowerCase(),
					text: message.sourceMsg,
					time: message.time,
					id: message.id,
					serverMsgId: message.id
				}
				chatHistroy[indexs].UpdateTime = new Date().getTime();
				chatHistroy[indexs].FromChatList ?chatHistroy[indexs].FromChatList.push(addJSON):chatHistroy[indexs].FromChatList=[addJSON]
				
			} else {
				console.log(' 不是用一个用户发送的')
				let {
					code,
					data
				} = await API$SelNickNameAvar({
					_id: message.from
				})
				if (code != 200) return $pub.Toast('请求失败~')

				chatHistroy.push({
					to: message.from, // 这边的to就是form
					Nickname: data.Nickname,
					avatar: data.avatar,
					UpdateTime: new Date().getTime(),
					FromChatList: [{
						SendType: 'text',
						text: message.sourceMsg,
						time: new Date().getTime(),
						id: data.id,
						serverMsgId: data.serverMsgId
					}]
				})
			}
		} else {
			console.log('不存在，添加全新的')
			let {
				code,
				data
			} = await API$SelNickNameAvar({
				_id: message.from
			})
			console.log('全新都添加记录')
			if (code != 200) return $pub.Toast('请求失败~')
			chatHistroy = [{
				to: message.from, // 这边的to就是form
				Nickname: data.Nickname,
				avatar: data.avatar,
				UpdateTime: new Date().getTime(),
				FromChatList: [{
					SendType: 'text',
					text: message.sourceMsg,
					time: new Date().getTime(),
					id: data.id,
					serverMsgId: data.serverMsgId
				}]
			}]
		}
		uni.setStorageSync(`chatHistroy_${uni.getStorageSync('UserInfo')._id}`, chatHistroy)
		uni.$emit('ListentMassage') //往聊天页面发送信息
	},
	onEmojiMessage: function(message) {
		console.warn('收到表情消息', message)
	},
	onPictureMessage: function(message) {
		console.warn('收到图片消息', message)
	},
	onCmdMessage: function(message) {
		console.warn('收到命令消息', message)
	},
	onAudioMessage: function(message) {
		console.warn('收到音频消息', message)
	},
	onLocationMessage: function(message) {
		console.warn('收到位置消息', message)
	},
	onFileMessage: function(message) {
		console.warn('收到文件消息', message)
	},
	onVideoMessage: function(message) {
		var node = document.getElementById('privateVideo');
		var option = {
			url: message.url,
			headers: {
				'Accept': 'audio/mp4'
			},
			onFileDownloadComplete: function(response) {
				var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
				node.src = objectURL;
			},
			onFileDownloadError: function() {
				console.log('File down load error.')
			}
		};
		WebIM.utils.download.call(conn, option);
	}, //收到视频消息
	onPresence: function(message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
	onRoster: function(message) {}, //处理好友申请
	onInviteMessage: function(message) {}, //处理群组邀请
	onOnline: function() {
		console.warn('本机网络连接成功', message)
	},
	onOffline: function() {
		console.warn('本机网络掉线', message)
	},
	onError: function(res) {
		console.log('失败回调', res)
		uni.showToast({
			title: res.data.data.error_description,
			icon: 'none',
			duration: 2500
		});
	}, //
	onBlacklistUpdate: function(list) { //黑名单变动
		// 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
		console.log(list);
	},
	onRecallMessage: function(message) {}, //收到撤回消息回调
	onReceivedMessage: function(message) {}, //收到消息送达服务器回执
	onDeliveredMessage: function(message) {}, //收到消息送达客户端回执
	onReadMessage: function(message) {
		console.log('收到消息已读回执', res)
	},
	onCreateGroup: function(message) {}, //创建群组成功回执（需调用createGroupNew）
	onMutedMessage: function(message) {} //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});


export default WebIM
